﻿using DrawTools.Serialize;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace DrawTools.Tools
{
    /// <summary>
    /// 画笔
    /// </summary>
    [SerializerType(typeof(DrawPenSerializer))]
    public sealed class PenDrawTool : DrawGeometryBase
    {
        #region 字段

        private List<Point> points = new List<Point>();

        protected override Point BeginingPoint => base.BeginingPoint.X != 0 ? base.BeginingPoint : pathGeometry?.Figures.Count == 0 ? new Point() : pathGeometry.Figures[0].StartPoint;
        #endregion 字段
        public PenDrawTool(DrawingCanvas drawingCanvas) : base(drawingCanvas)
        {
            DrawingToolType = DrawToolType.Pen;

            // 准备要处理的事件
            CanTouchDown = true;
        }

        #region 鼠标键盘事件

        public override bool OnTouchDown(int touchId, Point point)
        {
            TouchId = touchId;

            drawingCanvas.AddWorkingDrawTool(this);
            drawingCanvas.AddVisual(this);
            drawingCanvas.handleCursor = true;

            CanTouchDown = false;



            points.Add(point);

            geometry = new PathGeometry();

            var figure = new PathFigure { StartPoint = point };
            pathGeometry.Figures.Add(figure);

            CanTouchMove = true;
            CanTouchUp = true;

            if (TouchId != 0 || !drawingCanvas.CaptureMouse())
                CanTouchLeave = true;

            return true;
        }

        public override bool OnTouchMove(Point point)
        {
            if ((point - points.Last()).Length < Pen.Thickness)
                return true;

            points.Add(point);

            var figure = pathGeometry.Figures[0];
            var line = new LineSegment(point, IsStroked) { IsSmoothJoin = true };
            figure.Segments.Add(line);

            var dc = RenderOpen();
            dc.DrawGeometry(null, Pen, geometry);
            dc.Close();

            return true;
        }

        public override bool OnTouchUp(Point point)
        {
            if (points.Count < 2)
                drawingCanvas.DeleteVisual(this);
            else
            {
                geometry = geometry.GetWidenedPathGeometry(Pen);
                Draw();
            }

            drawingCanvas.DeleteWorkingDrawTool(this);

            IsFinish = true;

            CanTouchMove = false;
            CanTouchUp = false;
            CanTouchLeave = false;

            if (TouchId == 0 && drawingCanvas.IsMouseCaptured)
                drawingCanvas.ReleaseMouseCapture();

            drawingCanvas.handleCursor = false;

            return true;
        }

        #endregion 鼠标键盘事件
    }
}